package com.silverbox.sweeporder.common.util;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.sweeporder.controller.index.vo.ShopperConfigExtend;

import io.swagger.annotations.ApiModelProperty;

public class SweepOrderUtils {
	
    public static ShopperConfigExtend convertToShopperConfigVO(Map<String, Object> shopperConfig) {

	ShopperConfigExtend shopperConfigVO = new ShopperConfigExtend();
	if (shopperConfig == null) {
	    return null;
	}
	// 查询店铺消息推送方式
	Object aliyunMqttObj = shopperConfig.get("CTR_ALIYUN_MQTT");
	shopperConfigVO.setAliyunMqtt(aliyunMqttObj == null ? 0 : Integer.valueOf(aliyunMqttObj.toString()));
	// 默认阿里云消息
	shopperConfigVO.setAliyunMqtt(1);

	// 查询是否启呼叫服务
	Object callService = shopperConfig.get("CTR_CALL_SERVICE");
	shopperConfigVO.setCallService(callService == null ? 0 : Integer.valueOf(callService.toString()));

	// 查询轻快餐
	Object briskObj = shopperConfig.get("CRT_BRISK");
	shopperConfigVO.setBrisk(briskObj == null ? 0 : Integer.valueOf(briskObj.toString()));

	// 查询是否先付后吃
	Object firstPayMentObj = shopperConfig.get("CTR_SWEEP_FIRST_PAYMENT");
	shopperConfigVO.setFirstPayMent(firstPayMentObj == null ? 0 : Integer.valueOf(firstPayMentObj.toString()));

	// 查询是否开启选择人数，已经改为根据装修平台查询
	Object peopleNumberObj = shopperConfig.get("CTR_PEOPLE_SELECT");
	Integer peopleNumber = peopleNumberObj != null
	&& Integer.valueOf(peopleNumberObj.toString()).equals(new Integer(0))
	? 0 : 1;
	shopperConfigVO.setPeopleNumber(peopleNumber);
	/* if (peopleSelect == 0) {
	shopperConfigVO.setPeopleNumber(0);
	 }*/
	//shopperConfigVO.setPeopleNumber(0);

	// 是否开通扫码下单，默认开启
	Object isSweepOrderObj = shopperConfig.get("CTR_SWEEP_ORDER");
	Integer isOpenSweepOrder = (null == isSweepOrderObj || StringUtils.isEmpty(isSweepOrderObj.toString())) ? 1
		: Integer.valueOf(isSweepOrderObj.toString());
	shopperConfigVO.setIsOpenSweepOrder(isOpenSweepOrder);

	// 桌台名称前缀（大厅：001还是包厢：001）
	Object tableNameObj = shopperConfig.get("CTR_TABLE_NAME");
	String tableName = (null == tableNameObj || StringUtils.isEmpty(tableNameObj.toString())) ? "桌台"
		: tableNameObj.toString();
	shopperConfigVO.setTablePrefix(tableName);

	// 获取属性显示名称
	Object attrNameObj = shopperConfig.get("CTR_SWEEP_ATTRNAME");
	String attrName = (null == attrNameObj || StringUtils.isEmpty(attrNameObj.toString())) ? "备注"
		: attrNameObj.toString();
	shopperConfigVO.setAttrName(attrName);

	// 查询是否关闭会员卡支付
	Object vipPayObj = shopperConfig.get("CTR_SWEEP_CLOSE_VIP_PAY");
	shopperConfigVO.setIsVipPay(vipPayObj == null ? 0 : Integer.valueOf(vipPayObj.toString()));

	// 查询扫码下单点餐有无图形模式
	Object menuModeObj = shopperConfig.get("CTR_SWEEP_MENUTYPE");
	Integer menuType = (menuModeObj == null || "0".equals(String.valueOf(menuModeObj))) ? 1
		: Integer.valueOf(menuModeObj.toString());
	shopperConfigVO.setMenuType(menuType);

	// 是否支持柜台收银
	Object cashPayObj = shopperConfig.get("CRT_COUNTER_CASH_PAY");
	Integer cashPay = cashPayObj != null && Integer.valueOf(cashPayObj.toString()).equals(new Integer(1)) ? 1 : 0;
	// 只有先吃后付存在柜台收银
	if (new Integer(0).equals(shopperConfigVO.getFirstPayMent())) {
	    shopperConfigVO.setCashPay(cashPay);
	} else {
	    shopperConfigVO.setCashPay(0);
	}

	// 是否支持数据回流
	Object onlineDataBackflowObj = shopperConfig.get("ONLINE_ORDER_DATA_BACKFLOW");
	Integer onlineDataBackflow = (onlineDataBackflowObj == null || StringUtils.isEmpty(String.valueOf(onlineDataBackflowObj))) ? 0
		: Integer.valueOf(String.valueOf(onlineDataBackflowObj));
	shopperConfigVO.setOnlineDataBackflow(onlineDataBackflow);

	// 餐具费
		Double boxPrice = (shopperConfig.get("CTR_BOX_PRICE") == null
				|| StringUtils.isEmpty(String.valueOf(shopperConfig.get("CTR_BOX_PRICE")))) ? 0d
						: Double.valueOf(String.valueOf(shopperConfig.get("CTR_BOX_PRICE")));
		shopperConfigVO.setBoxPrice(boxPrice);

	// 获取打包费
		Double bagPrice = (shopperConfig.get("CTR_BAG_PRICE") == null
				|| StringUtils.isEmpty(String.valueOf(shopperConfig.get("CTR_BAG_PRICE")))) ? 0d
						: Double.valueOf(String.valueOf(shopperConfig.get("CTR_BAG_PRICE")));
		shopperConfigVO.setBagPrice(bagPrice);

	// 是否会员连锁
	Integer isChainStore = (null == shopperConfig.get("CTR_VIP_CHAIN_STORE")
		|| Utils.isEmpty(shopperConfig.get("CTR_VIP_CHAIN_STORE").toString())) ? 0
			: Integer.valueOf(shopperConfig.get("CTR_VIP_CHAIN_STORE").toString());
	shopperConfigVO.setIsChainStore(isChainStore);

	// 查询是否开启分时段售卖
	Integer openSaleInteral = (shopperConfig.get("IS_OPEN_SALE_INTERVAL") == null) ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_SALE_INTERVAL")));
	shopperConfigVO.setOpenSaleInteral(openSaleInteral);

	// 商家自定义本周最火显示数量
	Integer hotQuantity = (StringUtils.isEmpty(String.valueOf(shopperConfig.get("CTR_SWEEP_HOT_QUANTITY")))) ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_HOT_QUANTITY")));
	shopperConfigVO.setHotQuantity(hotQuantity);

	// 商家自定义是否启用手动优先
	Integer hotLevel = (shopperConfig.get("CTR_SWEEP_IS_HAND") == null) ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_IS_HAND")));
	shopperConfigVO.setHotLevel(hotLevel);

	// 商家配置清空购物车时间
	Integer clearCartObj = (shopperConfig.get("CTR_SWEEP_CLEAR_CART") == null
		|| StringUtils.isEmpty(shopperConfig.get("CTR_SWEEP_CLEAR_CART").toString()) 
		|| "默认".equals(shopperConfig.get("CTR_SWEEP_CLEAR_CART").toString()) 
		|| Integer.valueOf(shopperConfig.get("CTR_SWEEP_CLEAR_CART").toString()) > 60) ? 0
			: Integer.valueOf(shopperConfig.get("CTR_SWEEP_CLEAR_CART").toString());
	shopperConfigVO.setClearCartTime(clearCartObj);

	// 是否开通口碑正餐
	Integer koubeiDinner = StringUtils.isEmpty(String.valueOf(shopperConfig.get("CTR_KOUBEI_DINNER"))) ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_KOUBEI_DINNER")));
	shopperConfigVO.setKoubeiDinner(koubeiDinner);
	
	// add by yxy 2019年4月2日 是否开启扫码点餐先吃后付同桌单点
	Integer isOpenDeskmateSinglePoint = (shopperConfig.get("IS_OPEN_DESKMATE_SINGLEPIONT") == null 
		|| StringUtils.isEmpty(shopperConfig.get("IS_OPEN_DESKMATE_SINGLEPIONT").toString())) ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_DESKMATE_SINGLEPIONT")));
	shopperConfigVO.setIsOpenDeskmateSinglePoint(isOpenDeskmateSinglePoint);
	
	// -----------------------在线订单配置--------------------

	// 店铺是否开启智能取餐柜
	Object intelligenceCabinetObj = shopperConfig.get("CTR_OPEN_INTELLIGENCE_CABINET");
	Integer intelligenceCabinet = intelligenceCabinetObj == null ? 0
		: Integer.valueOf(String.valueOf(intelligenceCabinetObj));
	shopperConfigVO.setIntelligenceCabinet(intelligenceCabinet);

	// 商品是否开启外卖服务
	Integer openWaimai = shopperConfig.get("IS_OPEN_WAIMAI") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_WAIMAI")));
	shopperConfigVO.setOpenWaimai(openWaimai);

	// 是否开启在线订单服务 默认开启
	Integer onlineOrder = shopperConfig.get("CTR_ONLINE_ORDER") == null ? 1
		: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_ONLINE_ORDER")));
	shopperConfigVO.setOnlineOrder(onlineOrder);

	// 在线订单是否开启核销 默认需要核销
	Integer openHexiao = shopperConfig.get("CTR_ONLINE_NEED_HEXIAO") == null ? 1
		: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_ONLINE_NEED_HEXIAO")));
	shopperConfigVO.setOpenHexiao(openHexiao);

	// 在线订单订单序号新增首字符，暂时只改网络订单
	Integer initOrderSeq = shopperConfig.get("CTR_SWEEP_INITIALS_ORDER_SEQ") == null
		|| StringUtils.isEmpty(String.valueOf(shopperConfig.get("CTR_SWEEP_INITIALS_ORDER_SEQ"))) ? null
			: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_INITIALS_ORDER_SEQ")));
	shopperConfigVO.setInitOrderSeq(initOrderSeq);

	// 在线订单开启预订单（自提时商品限购数量）
	Integer purchaseNum = shopperConfig.get("CTR_ONLINE_PURCHASE_NUM") == null
		|| StringUtils.isEmpty(String.valueOf(shopperConfig.get("CTR_ONLINE_PURCHASE_NUM"))) ? 0
			: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_ONLINE_PURCHASE_NUM")));
	shopperConfigVO.setPurchaseNum(purchaseNum);

	// 在线订单下是否开通预点单（自提）
	Integer onlinePreOrder = shopperConfig.get("CTR_ONLINE_PRE_ORDER") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("CTR_ONLINE_PRE_ORDER")));
	shopperConfigVO.setOnlinePreOrder(onlinePreOrder);

	// 取餐柜是否开通短信通知
	Object onlinePreMsgPushObj = shopperConfig.get("CTR_KOUBEI_MSG_PUSH");
	Integer onlinePreMsgPush = (onlinePreMsgPushObj == null
		|| StringUtils.isEmpty(String.valueOf(onlinePreMsgPushObj))) ? 1
			: Integer.valueOf(String.valueOf(onlinePreMsgPushObj));
	shopperConfigVO.setOnlinePreMsgPush(onlinePreMsgPush);

	// 取餐柜订单是否开启KDS
	Integer isOpenKDS = shopperConfig.get("IS_OPEN_KDS") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_KDS")));
	shopperConfigVO.setIsOpenKDS(isOpenKDS);
	
	// 扫码点餐是否开启订单锁
	Integer isOpenOrderLock = shopperConfig.get("IS_OPEN_ORDER_LOCK") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_ORDER_LOCK")));
	shopperConfigVO.setIsOpenOrderLock(isOpenOrderLock);
	
	// 开具发票是否开启
	Integer isOpenInvoice = shopperConfig.get("IS_OPEN_INVOICE") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_INVOICE")));
	shopperConfigVO.setIsOpenInvoice(isOpenInvoice);

	Integer isGoodsSizeDefault=shopperConfig.get("IS_GOODS_SIZE_DEFAULT_SHOW")==null?0
            :Integer.valueOf(String.valueOf(shopperConfig.get("IS_GOODS_SIZE_DEFAULT_SHOW")));
	shopperConfigVO.setIsGoodsSizeDefaultShow(isGoodsSizeDefault);
	
	// 是否支持预约配送
	Integer reserveTakeout=shopperConfig.get("CTR_SWEEP_RESERVE_TAKEOUT")==null?0
            :Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_RESERVE_TAKEOUT")));
	shopperConfigVO.setReserveTakeout(reserveTakeout);
	
	// 是否开启员工验证
	Integer employeeInvalid=shopperConfig.get("CTR_SWEEP_EMPLOYEE_INVALID")==null?0
            :Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_EMPLOYEE_INVALID")));
	shopperConfigVO.setEmployeeInvalid(employeeInvalid);
	
	// 是否支持预约核销
	Integer reserveHexiao=shopperConfig.get("CTR_SWEEP_RESERVE_HEXIAO")==null?0
            :Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_RESERVE_HEXIAO")));
	shopperConfigVO.setReserveHexiao(reserveHexiao);
	
	// 扫描点餐是否开启预约点餐时间
	Integer reserveTime=shopperConfig.get("IS_SWEEP_RESERVE_TIME")==null?0
	         :Integer.valueOf(String.valueOf(shopperConfig.get("IS_SWEEP_RESERVE_TIME")));
	shopperConfigVO.setReserveTime(reserveTime);
	
	// 在线订单是否显示就餐方式选择
	Integer dineType=shopperConfig.get("CTR_ONLINE_SHOW_DINING_MODE")==null?0
		     :Integer.valueOf(String.valueOf(shopperConfig.get("CTR_ONLINE_SHOW_DINING_MODE")));
	shopperConfigVO.setDineType(dineType);	
	
	// 扫码付即时打印
	Integer sweepPayPrint = Utils.isEmpty(shopperConfig.get("CTR_SWEEP_PAY_PRINT"))?0
			:Integer.valueOf(shopperConfig.get("CTR_SWEEP_PAY_PRINT").toString());
	shopperConfigVO.setSweepPayPrint(sweepPayPrint);
	
	// 是否启用Redis集成扫码下单
	Integer sweepRedis=shopperConfig.get("CTR_SWEEP_REDIS")==null?0
	          :Integer.valueOf(String.valueOf(shopperConfig.get("CTR_SWEEP_REDIS")));
	shopperConfigVO.setSweepRedis(sweepRedis);

/*	// 微信公众号推广链接
	String wechatAppid = shopperConfig.get("WECHAT_APPID") == null ? "" : String.valueOf(shopperConfig.get("WECHAT_APPID"));
	shopperConfigVO.setWechatAppid(wechatAppid);	
	
	// 支付宝生活号推广链接
	String alipayAppid = shopperConfig.get("ALIPAY_APPID") == null ? "" : String.valueOf(shopperConfig.get("ALIPAY_APPID"));
	shopperConfigVO.setAlipayAppid(alipayAppid);*/
	
	// 是否启用外卖
	Integer isOpenWaimai = shopperConfig.get("IS_OPEN_WAIMAI") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_WAIMAI")));
	shopperConfigVO.setIsOpenWaimai(isOpenWaimai);
	
	// 是否开启店内消费 默认开启为1
	Integer isOpenStore = shopperConfig.get("IS_OPEN_IN_STORE_USE") == null ? 1
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_IN_STORE_USE")));
	shopperConfigVO.setIsOpenStore(isOpenStore);
	
	// 是否开启外卖配送功能
	Integer isOpenWaimaiDeliver = shopperConfig.get("IS_OPEN_WAIMAI_DELIVERY") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_WAIMAI_DELIVERY")));
	shopperConfigVO.setIsOpenWaimaiDeliver(isOpenWaimaiDeliver);
	
	// 是否开启外卖自提功能
	Integer isOpenWaimaiMention = shopperConfig.get("IS_OPEN_WAIMAI_MENTION") == null ? 0
		: Integer.valueOf(String.valueOf(shopperConfig.get("IS_OPEN_WAIMAI_MENTION")));
	shopperConfigVO.setIsOpenWaimaiMention(isOpenWaimaiMention);
	
	//扫门店码是否支持外卖 
	Integer shopQRIsSupportTakeways = shopperConfig.get("SHOPQR_IS_SUPPORT_TAKEWAYS") == null ? 0
			: Integer.valueOf(String.valueOf(shopperConfig.get("SHOPQR_IS_SUPPORT_TAKEWAYS")));
		shopperConfigVO.setShopQRIsSupportTakeways(shopQRIsSupportTakeways);

    shopperConfigVO.setSetGoodsUserVipPriceMode(Integer.valueOf(Optional.ofNullable(shopperConfig.get("SET_GOODS_USER_VIP_PRICE_MODE")).orElse(1).toString()));
    return shopperConfigVO;

    }

    /**
     * 拼接订单序号，不足4位补足
     * 
     * @param
     * @return
     */
    public static String getOrderSeq(String orderSeqStr) {
		if (null == orderSeqStr) {
		    return "0000";
		} else {
		    if (orderSeqStr.length() == 1) {
			return "000" + orderSeqStr;
		    } else if (orderSeqStr.length() == 2) {
			return "00" + orderSeqStr;
		    } else if (orderSeqStr.length() == 1) {
			return "0" + orderSeqStr;
		    } else {
			return orderSeqStr;
		    }
		}
    }
    
	/**
	 * 转发请求
	 * @param url 请求地址 
	 * @param jsonData json对象
	 * @param timeoutConnection     设置连接超时时间（毫秒）
	 * @param timeoutSocket			设置默认的套接字超时（so_timeout毫秒）。这是为了等待数据超时。
	 * @param charset  编码格式
	 * @return String 请求返回结果
	 */
	public static String buildJsonRquest(String url, String jsonData,int timeoutConnection,int timeoutSocket,
			String charset) {
		String response = "";
//		//构造HttpClient的实例  
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();  
//		//根据默认超时限制初始化requestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutSocket).setConnectTimeout(timeoutConnection).build();
		try {
			StringEntity entity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);	//构造请求数据
			HttpPost httpPost = new HttpPost(url);  
	        httpPost.setConfig(requestConfig);	//设置请求器的配置
	        httpPost.setEntity(entity);	//设置请求体
			//使用execute方法发送HTTP Post请求，并返回HttpResponse对象  
			HttpResponse httpResponse = httpClient.execute(httpPost);  
			int statusCode = httpResponse.getStatusLine().getStatusCode();  
			if(statusCode==HttpStatus.SC_OK){  
				response = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");  
			}else{  
				response = "{\"error_response\":\"request failed\"}";
			}
		}catch (ClientProtocolException e) {
			e.printStackTrace();
			response = "{\"is_success\":\"F\",\"error_code\":\"ClientProtocolException\"}";
		} catch (IllegalStateException e) {
			e.printStackTrace();
			response = "{\"is_success\":\"F\",\"error_code\":\"IllegalStateException\"}";
		} catch (IOException e) {
			e.printStackTrace();
			response = "{\"is_success\":\"F\",\"error_code\":\"IOException\"}";
		} catch (Exception e) {
			e.printStackTrace();
			response = "{\"is_success\":\"F\",\"error_code\":\""+e.getMessage()+"\"}";
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	    return response;
	}
}
